package com.example.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.museum.entity.ShoppingCart;
import com.example.museum.entity.Product;
import com.example.museum.mapper.ShoppingCartMapper;
import com.example.museum.mapper.ProductMapper;
import com.example.museum.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
//ToDo 需要修改
@Service
public class CartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements CartService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<ShoppingCart> getCartItemsByUserId(Long userId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        return list(queryWrapper);
    }

    @Override
    @Transactional
    public void addToCart(ShoppingCart shoppingCart) {
        // 先查询购物车是否已存在该商品
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                   .eq(ShoppingCart::getProductId, shoppingCart.getProductId());
        
        ShoppingCart existItem = getOne(queryWrapper);
        
        if (existItem != null) {
            // 如果已存在，增加数量
            existItem.setQuantity(existItem.getQuantity() + shoppingCart.getQuantity());
            updateById(existItem);
        } else {
            // 不存在则插入新记录
            // 获取商品信息
            Product product = productMapper.selectById(shoppingCart.getProductId());
            shoppingCart.setProductName(product.getName());
            shoppingCart.setProductImage(product.getImage());
            shoppingCart.setPrice(product.getPrice());
            shoppingCart.setSelected(true);
            
            save(shoppingCart);
        }
    }

    @Override
    public void updateCartItemQuantity(Long cartItemId, Integer quantity) {
        LambdaUpdateWrapper<ShoppingCart> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShoppingCart::getId, cartItemId)
                    .set(ShoppingCart::getQuantity, quantity);
        update(updateWrapper);
    }

    @Override
    public void removeCartItem(Long cartItemId) {
        removeById(cartItemId);
    }

    @Override
    public void clearCart(Long userId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        remove(queryWrapper);
    }
}